/**
 * Title :	Property view
 * Description: Property editor
 * Version:	provider
 * Copyright (c) 2001-2008
 * Terms of use:see license agreement at http://treebolic.sourceforge.net/en/license.htm
 * Author: Bernard Bou
 * Company: bsys
 */
package bsys.propertyview;

import java.awt.Component;
import java.util.Map;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;

/**
 * List editor
 * 
 * @author Bernard Bou
 */
class ListEditor extends DefaultCellEditor
{
	private static final long serialVersionUID = 1L;

	/**
	 * String to image map
	 */
	private Map<String, ImageIcon> theImageMap = null;

	/**
	 * Constructor
	 */
	public ListEditor()
	{
		super(new JComboBox());

		DefaultListCellRenderer thisRenderer = new DefaultListCellRenderer()
		{
			private static final long serialVersionUID = 1L;

			public Component getListCellRendererComponent(JList thisList, Object thisValue, int index, boolean isSelected, boolean cellHasFocus)
			{
				if (theImageMap == null)
				{
					return super.getListCellRendererComponent(thisList, thisValue, index, isSelected, cellHasFocus);
				}

				ImageIcon thisIcon = theImageMap.get(thisValue);
				setText(thisValue == null ? PropertyView.theDefaultString : (String) thisValue);
				setIcon(thisIcon);
				setBackground(isSelected ? thisList.getSelectionBackground() : thisList.getBackground());
				setForeground(isSelected ? thisList.getSelectionForeground() : thisList.getForeground());
				return this;
			}
		};
		thisRenderer.setHorizontalAlignment(JLabel.LEFT);
		thisRenderer.setVerticalAlignment(JLabel.CENTER);
		thisRenderer.setOpaque(true);
		getComboBox().setRenderer(thisRenderer);
	}

	/**
	 * Get access to combobox component
	 * 
	 * @return combo box component
	 */
	public JComboBox getComboBox()
	{
		return (JComboBox) editorComponent;
	}

	/**
	 * Allow for edit line
	 * 
	 * @param thisFlag
	 *        true/false
	 */
	public void setEditable(boolean thisFlag)
	{
		getComboBox().setEditable(thisFlag);
	}

	/**
	 * Render strings as images (as per map)
	 * 
	 * @param thisImageMap
	 *        string to image map
	 */
	public void setImageMap(Map<String, ImageIcon> thisImageMap)
	{
		theImageMap = thisImageMap;
	}

	// I N T E R F A C E

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.DefaultCellEditor#getCellEditorValue()
	 */
	@Override
	public Object getCellEditorValue()
	{
		String thisValue = (String) super.getCellEditorValue();
		if (thisValue == null || thisValue.equals(PropertyView.theDefaultString))
			return null;
		return thisValue;
	}
}
